#
# This file is part of Contentbus

# Contentbus is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# Contentbus is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with Contentbus.  If not, see <http://www.gnu.org/licenses/>.

"""Builtin match operators"""

BUILTIN_OPERATORS = {}


def register_builtin_operators(registry):
    """
    Register operators to a registry.

    @param registry: the registry to register operator to.
    """
    for name, operator in BUILTIN_OPERATORS.iteritems():
        registry.register(operator, name, overwrite=True)


def _register_builtin(name):
    """Decorator to register  builtin operators"""

    def register(operator):
        BUILTIN_OPERATORS[name] = operator
        return operator

    return register


@_register_builtin("eq")
def op_eq(value, attr_name=None, obj=None):
    return getattr(obj, attr_name) == value


@_register_builtin("is")
def op_is(value, attr_name=None, obj=None):
    return getattr(obj, attr_name) is value


@_register_builtin("exists")
def op_exists(value, attr_name=None, obj=None):
    return not(hasattr(obj, attr_name) ^ value)


@_register_builtin("in_range")
def op_in_range(start, end, attr_name=None, obj=None):
    return start <= getattr(obj, attr_name) <= end


@_register_builtin("len")
def op_len(length, attr_name=None, obj=None):
    return len(getattr(obj, attr_name)) == length
